package com.adams.custom.page.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.adams.core.exception.BusinessException;

public class ViewUtil
{
	private static Logger logger = Logger.getLogger(ViewUtil.class.getName());

	public static String createUuid()
	{
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	/**
	 * Description : 对象复制
	 * 
	 * @param src
	 * @return
	 * 
	 */
	public static Object cloneBean(Object src)
	{
		Object result = null;
		try
		{
			result = BeanUtils.cloneBean(src);
		} catch (IllegalAccessException e)
		{
			logger.error(e);
		} catch (InstantiationException e)
		{
			logger.error(e);
		} catch (InvocationTargetException e)
		{
			logger.error(e);
		} catch (NoSuchMethodException e)
		{
			logger.error(e);
		}

		return result;
	}

	/**
	 * Description : 序列化方式 对象复制
	 * 
	 * @param src
	 * @return
	 * 
	 */
	public static Object cloneBeanByStream(Object src)
	{
		Object result = null;
		try
		{
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(byteOut);
			out.writeObject(src);

			ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut
					.toByteArray());
			ObjectInputStream in = new ObjectInputStream(byteIn);
			result = in.readObject();
		} catch (IOException e)
		{
			logger.error(e);
		} catch (ClassNotFoundException e)
		{
			logger.error(e);
		}
		return result;
	}

	/**
	 * Description : 把对象转换成Map形式
	 * 
	 * @param srcObject
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static Map Object2Map(Object srcObject)
	{
		Map result = new HashMap();

		if (srcObject instanceof Map)
		{
			return (Map) srcObject;
		}

		BeanMap beanMap = new BeanMap(srcObject);
		Set keys = beanMap.keySet();
		Iterator keyIterator = keys.iterator();
		while (keyIterator.hasNext())
		{
			String propertyName = (String) keyIterator.next();
			Object value = beanMap.get(propertyName);
			if (null != value)
			{
				if (value instanceof String && "".equals(value))
				{
					continue;
				}
				result.put(propertyName, value);
			}
		}
		return result;
	}

	/**
	 * Description : 把Map转对象
	 * 
	 * @param inputMap
	 * @param className
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static Object map2Object(Map inputMap, Class className)
	{
		Object result = null;
		try
		{
			result = className.newInstance();
			BeanUtils.populate(result, inputMap);
		} catch (InvocationTargetException e)
		{
			logger.error(e);
		} catch (InstantiationException e)
		{
			logger.error(e);
		} catch (IllegalAccessException e)
		{
			logger.error(e);
		}
		return result;
	}

	/**
	 * Description : 根据_后字母转大写规则 把对象列表转换成数据库字段名Map对象列表
	 * 
	 * @param objects
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static List<Map> Objects2ColumnMapsBy_C(List objects)
	{
		List<Map> result = new ArrayList<Map>();
		if (null != objects && objects.size() > 0)
		{
			int len = objects.size();
			for (int i = 0; i < len; i++)
			{
				Object object = objects.get(i);
				Map columnMap = Object2ColumnMapBy_C(object);
				result.add(columnMap);
			}
		}
		return result;
	}

	/**
	 * Description : 根据_后字母转大写规则 把对象转换成数据库字段名Map对象
	 * 
	 * @param objects
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static Map Object2ColumnMapBy_C(Object object)
	{
		Map objectMap = Object2Map(object);
		Map columnMap = ObjectMap2ColumnMapBy_C(objectMap);
		return columnMap;
	}

	/**
	 * Description : 根据_后字母转大写规则 把数据库字段名Map对象列表转换成对象列表
	 * 
	 * @param columnMaps
	 * @param className
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static List ColumnMaps2ObjectsBy_C(List<Map> columnMaps,
			Class className)
	{
		List result = new ArrayList();
		if (null != columnMaps && columnMaps.size() > 0)
		{
			for (Map columnMap : columnMaps)
			{
				Object object = ColumnMap2ObjectBy_C(className, columnMap);
				result.add(object);
			}
		}
		return result;
	}

	/**
	 * Description : 根据_后字母转大写规则 把数据库字段名Map对象转换成对象列表
	 * 
	 * @param columnMaps
	 * @param className
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static Object ColumnMap2ObjectBy_C(Class className, Map columnMap)
	{
		Map objectMap = ColumnMap2ObjectMapBy_C(columnMap);
		Object object = map2Object(objectMap, className);
		return object;
	}

	/**
	 * Description : 根据_后字母转大写规则 把对象属性Map对象列表转换成数据库字段名Map对象列表
	 * 
	 * @param objectMaps
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static List<Map> ObjectMaps2ColumnMapsBy_C(List<Map> objectMaps)
	{
		List<Map> result = new ArrayList<Map>();
		if (null != objectMaps && objectMaps.size() > 0)
		{
			for (Map objectMap : objectMaps)
			{
				Map columnMap = ObjectMap2ColumnMapBy_C(objectMap);
				result.add(columnMap);
			}
		}
		return result;
	}

	/**
	 * Description : 根据_后字母转大写规则 把数据库字段名Map对象列表转换成对象属性Map对象列表
	 * 
	 * @param columnMaps
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static List<Map> ColumnMaps2ObjectMapsBy_C(List<Map> columnMaps)
	{
		List<Map> result = new ArrayList<Map>();
		if (null != columnMaps && columnMaps.size() > 0)
		{
			for (Map columnMap : columnMaps)
			{
				Map objectMap = ColumnMap2ObjectMapBy_C(columnMap);
				result.add(objectMap);
			}
		}
		return result;
	}

	/**
	 * Description : 根据_后字母转大写规则 把对象属性Map对象转换成数据库字段名Map对象
	 * 
	 * @param objectMap
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static Map ObjectMap2ColumnMapBy_C(Map objectMap)
	{
		Map columnMap = new HashMap();
		if (objectMap.size() > 0)
		{
			Iterator entries = objectMap.entrySet().iterator();
			while (entries.hasNext())
			{
				Entry thisEntry = (Entry) entries.next();
				String key = thisEntry.getKey().toString();
				Object value = thisEntry.getValue();
				String columncode = attribute2columncodeBy_C(key);
				columnMap.put(columncode, value);
			}
		}
		return columnMap;
	}

	/**
	 * Description : 根据_后字母转大写规则 把数据库字段名Map对象转换成对象属性Map对象
	 * 
	 * @param columnMap
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static Map ColumnMap2ObjectMapBy_C(Map columnMap)
	{
		Map objectMap = new HashMap();
		if (columnMap.size() > 0)
		{
			Iterator entries = columnMap.entrySet().iterator();
			while (entries.hasNext())
			{
				Entry thisEntry = (Entry) entries.next();
				String key = thisEntry.getKey().toString();
				Object value = thisEntry.getValue();
				String attribute = columncode2attributeBy_C(key);
				objectMap.put(attribute, value);
			}
		}
		return objectMap;
	}

	/**
	 * Description : 根据_后字母转大写规则 把数据字段名转成属性
	 * 
	 * @param voName
	 * @return
	 * 
	 */
	private static String columncode2attributeBy_C(String voName)
	{
		StringBuilder sb = new StringBuilder();
		boolean flag = false;
		for (int i = 0; i < voName.length(); i++)
		{
			char cur = voName.charAt(i);
			if (cur == '_')
			{
				flag = true;

			} else
			{
				if (flag)
				{
					sb.append(Character.toUpperCase(cur));
					flag = false;
				} else
				{
					sb.append(Character.toLowerCase(cur));
				}
			}
		}
		return sb.toString();
	}

	/**
	 * Description : 根据大写字母前加_根据 把属性转成数据库字段名
	 * 
	 * @param voName
	 * @return
	 * 
	 */
	private static String attribute2columncodeBy_C(String voName)
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < voName.length(); i++)
		{
			char cur = voName.charAt(i);
			if (Character.isUpperCase(cur))
			{
				sb.append("_");
				sb.append(Character.toLowerCase(cur));
			} else
			{
				sb.append(cur);
			}
		}
		return sb.toString();
	}

	/**
	 * Description : String转换BigDecimal
	 * 
	 * @param v
	 * @param scale
	 * @return
	 * 
	 */
	public static BigDecimal round(String v, int scale)
	{
		if (scale < 0)
		{
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(v);
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP);
	}

	/**
	 * Description : 日期型转字符串
	 * 
	 * @param v
	 * @return
	 * 
	 */
	public static String Date2Str(java.util.Date v)
	{
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		String result = format1.format(v);
		return result;
	}

	/**
	 * Description : SQL时间转字符串
	 * 
	 * @param v
	 * @return
	 * 
	 */
	public static String Time2Str(java.util.Date v)
	{
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String result = format1.format(v);
		return result;
	}

	/**
	 * Description : 在url后面增加参数
	 * 
	 * @param url
	 * @param parameterName
	 * @param parameterValue
	 * @return
	 * 
	 */
	public static String addParameterToUrl(String url, String parameterName,
			String parameterValue)
	{
		if (!isNuLLStr(url) && !isNuLLStr(parameterValue))
		{
			StringBuilder result = new StringBuilder(url);
			if (result.indexOf("?") > 0)
			{
				result.append("&");
			} else
			{
				result.append("?");
			}
			result.append(parameterName);
			result.append("=");
			result.append(parameterValue);
			return result.toString();
		} else
		{
			return url;
		}
	}

	/**
	 * Description : 判断Map中key的值对象是否为空
	 * 
	 * @param str
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static boolean isNuLLValueInMap(Map map, String Key)
	{
		boolean result = true;
		if (null != map && map.containsKey(Key) && null != map.get(Key))
		{
			result = false;
		}
		return result;
	}

	/**
	 * Description : 判断是否空字符串
	 * 
	 * @param str
	 * @return
	 * 
	 */
	public static boolean isNuLLStr(String str)
	{
		boolean result = true;
		if (null != str && str.trim().length() > 0)
		{
			result = false;
		}
		return result;
	}

	/**
	 * Description : 判断字符串是否数值
	 * 
	 * @param numStr
	 * @return
	 * 
	 */
	public static boolean isNum(String numStr)
	{
		boolean result = false;
		if (!isNuLLStr(numStr) && numStr.matches("^(-?\\d+)(\\.\\d+)?$"))
		{
			result = true;
		}
		return result;
	}

	/**
	 * Description : 判断字符串是否正整数
	 * 
	 * @param intStr
	 * @return
	 * 
	 */
	public static boolean isInt(String intStr)
	{
		boolean result = false;
		if (!isNuLLStr(intStr) && intStr.matches("^[0-9]\\d*$"))
		{
			result = true;
		}
		return result;
	}

	/**
	 * Description : 判断字符串是否逻辑型
	 * 
	 * @param booleanStr
	 * @return
	 * 
	 */
	public static boolean isBoolean(String booleanStr)
	{
		boolean result = false;
		if (!isNuLLStr(booleanStr))
		{
			if ("true".equals(booleanStr) || "false".equals(booleanStr))
			{
				result = true;
			} else if ("1".equals(booleanStr) || "0".equals(booleanStr))
			{
				result = true;
			}
		}
		return result;
	}

	/**
	 * Description : 判断字符串是否日期型
	 * 
	 * @param dateStr
	 * @return
	 * 
	 */
	public static boolean isDate(String dateStr)
	{
		boolean result = false;
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
		if (!isNuLLStr(dateStr))
		{
			try
			{
				simpleDate.parse(dateStr);
				result = true;
			} catch (ParseException e)
			{
				logger.error(e);
			}
		}
		return result;
	}

	/**
	 * Description : 判断字符串是否时间型
	 * 
	 * @param dateStr
	 * @return
	 * 
	 */
	public static boolean isTime(String dateStr)
	{
		boolean result = false;
		SimpleDateFormat simpleDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		if (!isNuLLStr(dateStr))
		{
			try
			{
				simpleDate.parse(dateStr);
				result = true;
			} catch (ParseException e)
			{
				logger.error(e);
			}
		}
		return result;
	}

	/**
	 * Description : 处理mysql特殊字符 给新增修改删除使用
	 * 
	 * @param value
	 * @return
	 * 
	 */
	public static String dealMysqlSpecialChar(String value)
	{
		String result = "";
		if (!isNuLLStr(value))
		{
			result = value;
			if (result.contains("'"))
			{
				result = result.replaceAll("'", "''");
			}
			if (result.contains("\\"))
			{
				result = result.replaceAll("\\\\", "\\\\\\\\");
			}
		}
		return result;
	}

	/**
	 * Description : 处理mysql特殊字符给查询使用
	 * 
	 * @param value
	 * @return
	 * 
	 */
	public static String dealMysqlSpecialCharToSearch(String value)
	{
		String result = "";
		if (!isNuLLStr(value))
		{
			result = value;
			if (result.contains("'"))
			{
				result = result.replace("'", "''");
			}
			if (result.contains("%"))
			{
				result = result.replace("%", "\\%");
			}
			if (result.contains("_"))
			{
				result = result.replace("_", "\\_");
			}
		}
		return result;
	}

	/**
	 * Description : 得到页面控件id(用于把页面回传的页面控件id转化为页面控件的数据库实体id)
	 * 
	 * @param idStr
	 * @return
	 * @throws BusinessException
	 * 
	 */
	public static Long getViewControlId(String idStr) throws BusinessException
	{
		Long id = Long.valueOf(0);
		if (isNuLLStr(idStr))
		{
			return id;
		}
		idStr = idStr.trim();
		int len = idStr.length();
		int beginpos = 0;
		for (int i = 0; i < len; i++)
		{
			beginpos = i;
			int chr = idStr.charAt(i);
			if (Character.isDigit(chr))
			{
				break;
			}
		}
		int endpos = idStr.indexOf("_");
		if (beginpos < endpos && endpos > 0)
		{
			idStr = idStr.substring(beginpos, endpos);
		}
		if (ViewUtil.isNum(idStr))
		{
			id = Long.valueOf(idStr);
		}
		return id;
	}

	/**
	 * Description : 得到页面上多选的数据信息
	 * 
	 * @param inputMap
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static List<Map> getMultiChoiceData(Map inputMap)
	{
		List<Map> mapList = new ArrayList<Map>();

		String dataStr = (String) inputMap.get(ViewConstant.VIEW_DATA_PARAM);
		if (!ViewUtil.isNuLLStr(dataStr))
		{
			JSONObject data = JSONObject.fromObject(dataStr);
			JSONArray items = data.getJSONArray(ViewConstant.JSON_ITEMS);
			if (null != items)
			{
				for (int i = 0; i < items.size(); i++)
				{
					JSONObject item = items.getJSONObject(i);
					Map map = (Map) JSONObject.toBean(item, HashMap.class);
					Iterator keyIt = map.keySet().iterator();
					while (keyIt.hasNext())
					{
						String key = (String) keyIt.next();
						Object value = map.get(key);
						if (null != value)
						{
							if (!(value instanceof String))
							{
								map.put(key, value.toString());
							}
						}
					}
					mapList.add(map);
				}
			}
		}
		return mapList;
	}

	/**
	 * Description : 使用系统时间产生随机数值
	 * 
	 * @return
	 * 
	 */
	public static Long getRandomLongBySystemTime()
	{
		Long result = null;
		long time = System.currentTimeMillis();
		result = Long.valueOf(time);
		return result;
	}

	/**
	 * Description : 根据分隔符 分隔字符串 得到字符串列表
	 * 
	 * @param str
	 * @param seq
	 * @return
	 * 
	 */
	public static List<String> getListBySeq(String str, String seq)
	{
		List<String> result = new ArrayList<String>();
		if (isNuLLStr(seq) && !isNuLLStr(str))
		{
			result.add(str);
			return result;
		}
		if (!isNuLLStr(str))
		{
			StringTokenizer st = new StringTokenizer(str, seq);
			while (st.hasMoreTokens())
			{
				String column = st.nextToken();
				if (null != column && !"".equals(column.trim()))
				{
					result.add(column);
				}
			}
		}
		return result;
	}

	public static void main(String[] args) throws Exception
	{
		String idStr = ",  8900600_ViewPanel";
		Long id = getViewControlId(idStr);
		System.out.println(id);
		StringBuilder ckeckSql = new StringBuilder();
		ckeckSql.append("(1=1 and 1=1 ) @or ");
		ckeckSql.append("(1=1 and 1=1 ) @or ");
		ckeckSql.append("(1=1 and 1=1 ) @or ");
		ckeckSql.delete(ckeckSql.length() - 3, ckeckSql.length());
		System.out.println(ckeckSql.toString());

	}
}
